<template>
	<div class="page-nearby">
		<div class="account_list" style="text-align: center">
			<text>搜索附近的控制器，下拉可刷新</text>
		</div>
		<div v-for="item in matchDevices" :key="item.ID" class="account_list">
			<text>信号强度：{{ item.RSSI }}</text>
			<text>设备编号：{{ item.ID }}</text>
			<text>设备状态：{{ remainReason[item.STATUS] }}</text>
			<text v-if="item.ORDERID > 0">当前订单：{{ item.ORDERID }}</text>
			<text v-if="item.REMAINTIME > 0">剩余时长：{{ item.REMAINSHOW }}</text>
			<text v-if="item.REMAINQUANTITY > 0">剩余数量：{{ item.REMAINQUANTITY }} (W.h / 脉冲 / 币)</text>
		</div>
	</div>
</template>

<script>
import utils from '@/utils';

export default {
	name: 'PageNearby',
	data: () => ({
		remainReason: {
			0: '通电停止',
			1: '启动中',
			2: '拔插断电',
			3: '过载断电',
			4: '短路断电',
			5: '充满断电',
			6: '主动断电',
			7: '订单覆盖',
			10: '电池电压低',
			30: '管理员停用',
			31: '库存用完',
			50: '淹水故障'
		},
		matchDevices: []
	}),
	onLoad() {
		uni.showLoading({ title: '正在搜索控制器' });
		this.searchDevice().catch((_) => false);
	},
	methods: {
		onPullDownRefresh() {
			this.searchDevice().catch((_) => false);
		},
		async searchDevice() {
			// #ifdef MP-WEIXIN
			const res = await utils.checkBluetooth().catch((_) => false);
			if (!res) {
				return;
			}
			// #endif
			const matchDevices = [];
			uni.openBluetoothAdapter({
				success: () => {
					uni.startBluetoothDevicesDiscovery({
						allowDuplicatesKey: true,
						interval: 100,
						complete: () => {
							let trycnt = 0;
							uni.onBluetoothDeviceFound((res) => {
								uni.showLoading({ title: '搜索控制器(' + trycnt + ')' });
								const devices = res.devices;
								for (let i = 0; i < devices.length; i++) {
									if (devices[i].advertisData) {
										const view = new Uint8Array(devices[i].advertisData);
										const checkDevice = utils.isChargeDevice(view);
										if (checkDevice && checkDevice.VID) {
											checkDevice.deviceId = devices[i].deviceId;
											checkDevice.RSSI = devices[i].RSSI;

											let checkExists = false;
											for (let j = 0; j < matchDevices.length; j++) {
												if (checkDevice.deviceId === matchDevices[j].deviceId && checkDevice.ID === matchDevices[j].ID) {
													checkExists = true;
													break;
												}
											}
											if (checkExists === false) {
												matchDevices.push(checkDevice);
											}
											if (devices[i].RSSI > -40) {
												trycnt = 100;
												break;
											}
										}
									}
								}

								if (trycnt >= 20) {
									if (uni.offBluetoothDeviceFound) {
										uni.offBluetoothDeviceFound((_) => null);
									}
									trycnt = 0;
									uni.stopBluetoothDevicesDiscovery({
										complete: () => {
											uni.closeBluetoothAdapter({
												complete: () => {
													const compare = function (prop) {
														return function (obj1, obj2) {
															let val1 = obj1[prop];
															let val2 = obj2[prop];
															if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
																val1 = Number(val1);
																val2 = Number(val2);
															}
															if (val1 < val2) {
																return -1;
															} else if (val1 > val2) {
																return 1;
															} else {
																return 0;
															}
														};
													};
													matchDevices.sort(compare('RSSI'));
													this.matchDevices = matchDevices;
													uni.hideLoading();
												}
											});
										}
									});
								}
								trycnt++;
							});
						}
					});
				},
				fail: () => {
					uni.hideLoading();
					uni.showModal({
						title: '提示',
						content: '蓝牙打开失败，请开启蓝牙',
						cancelText: '返回',
						confirmText: '刷新',
						success: (res) => {
							if (res.confirm) {
								uni.navigateBack()
								// uni.redirectTo({ url: '/others/pages/nearby/nearby' });
							} else if (res.cancel) {
								uni.navigateBack()
								// uni.redirectTo({ url: '/others/pages/getopen/getopen' })
							}
						}
					});
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.page-nearby {
	background-color: #f9f9f9;
}
</style>